package com.example.shiwu;

import static com.example.shiwu.util.StringUtil.get;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.shiwu.db.model.Items;
import com.example.shiwu.fragment.MainRoutineFragment;
import com.example.shiwu.fragment.MainInfoFragment;
import com.example.shiwu.fragment.MainStatusFragment;
import com.example.shiwu.fragment.MainSystemFragment;
import com.example.shiwu.fragment.MyFragment;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.util.NetworkUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup rg_tab_bar;
    private RadioButton rb_channel;

    //Fragment Object
    private MainRoutineFragment fg1;
    private MainInfoFragment fg2;
    private MainStatusFragment fg3;
    private MainSystemFragment fg4;
    private MyFragment fg5;
    private FragmentManager fManager;
    private RadioButton[] rbs;
    private Map<Integer, Integer> al;
    private ItemsService itemsService;
    private Context myContext;
//    private final int STATE_DISCONNECTED = 1;
//    private final int STATE_CONNECTING = 2;
//    private final int STATE_CONNECTED = 3;
//    private int mSocketConnectState = STATE_DISCONNECTED;
//    private static final int MSG_TIME_SEND = 1;
//    private static final int MSG_SOCKET_CONNECT = 2;
//    private static final int MSG_SOCKET_DISCONNECT = 3;
//    private static final int MSG_SOCKET_CONNECTFAIL = 4;
//    private static final int MSG_RECEIVE_DATA = 5;
//    private static final int MSG_SEND_DATA = 6;
//    public Socket mSocket;
//    private SocketConnectThread mConnectThread;
//    private SocketReceiveThread mReceiveThread;
//    private final int DEFAULT_PORT = 8086;
//    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
//    private OutputStream mOutStream;
//    private InputStream mInStream;
//    private Handler mSubThreadHandler;
//    private HandlerThread mHandlerThread;
//    private int success_count = 0;
//    private MyQueue queue;
//    private ArrayList<String> msgArray;
//    private DataParseUtil dataParseUtil;
//    private DeviceService deviceService;
//    private String itemsId;
//    private SharedPreferences mSharedPreferences;
//
//    private Handler mHandler = new Handler() {
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case MSG_TIME_SEND:
//                    break;
//                case MSG_SOCKET_CONNECT:
//                    mSocketConnectState = STATE_CONNECTED;
//                    System.out.println(R.string.disconnect);
//                    mReceiveThread = new SocketReceiveThread();
//                    mReceiveThread.start();
//                    break;
//                case MSG_SOCKET_DISCONNECT:
//                    System.out.println(R.string.connect);
//                    mSocketConnectState = STATE_DISCONNECTED;
//                    closeConnection();
//                    break;
//                case MSG_SOCKET_CONNECTFAIL:
//                    mSocketConnectState = STATE_DISCONNECTED;
//                    System.out.println("======================连接失败=========================");
//                    mReceiveThread = new SocketReceiveThread();
//                    mReceiveThread.start();
//                    break;
//                case MSG_RECEIVE_DATA:
//
//                    break;
//                default:
//                    break;
//            }
//        }
//
//        ;
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 打印MainActivity实例ID，判断是否重建
        Log.d("MainActivity", "实例ID：" + this.hashCode() + "，是否重建：" + (savedInstanceState != null));

        // 若使用Fragment，打印默认Tab的实例ID
        if (savedInstanceState == null) {
            // 首次创建时初始化默认Tab
            fManager = getSupportFragmentManager();
            setMainTab();
            rg_tab_bar = (RadioGroup) findViewById(R.id.rg_tab_bar);
            rg_tab_bar.setOnCheckedChangeListener(this);
            //获取第一个单选按钮，并设置其为选中状态
            rb_channel = (RadioButton) findViewById(R.id.rb_maininfo);
            rb_channel.setChecked(true);
            itemsService = new ItemsService();
            myContext = this;
        } else {
            // 重建时从FragmentManager获取已存在的默认Tab
            fManager = getSupportFragmentManager();
            setMainTab();
            rg_tab_bar = (RadioGroup) findViewById(R.id.rg_tab_bar);
            rg_tab_bar.setOnCheckedChangeListener(this);
            //获取第一个单选按钮，并设置其为选中状态
//            rb_channel = (RadioButton) findViewById(R.id.rb_main);
//            rb_channel.setChecked(true);
            itemsService = new ItemsService();
            myContext = this;
        }

    }


    //设置导航图片的大小
    private void setMainTab() {
        rbs = new RadioButton[3];
        //初始化控件，中间大个的，周围小弟
        rbs[0] = (RadioButton) findViewById(R.id.rb_main);
        rbs[1] = (RadioButton) findViewById(R.id.rb_maininfo);
        // rbs[2] = (RadioButton) findViewById(R.id.rb_mainstatus);
//        rbs[3] = (RadioButton) findViewById(R.id.rb_system);
        rbs[2] = (RadioButton) findViewById(R.id.rb_mine);
        al = new HashMap<Integer, Integer>();
        al.put(R.id.rb_main, R.drawable.label_mainprogram_n);
        al.put(R.id.rb_maininfo, R.drawable.label_session_n);
        // al.put(R.id.rb_mainstatus,R.drawable.label_state_n);
//        al.put(R.id.rb_system,R.drawable.label_calibration_n);
        al.put(R.id.rb_mine, R.drawable.label_my_n);

        for (RadioButton rb : rbs) {
            //挨着给每个RadioButton加入drawable限制边距以控制显示大小
            Drawable[] drs = rb.getCompoundDrawables();
            //获取drawables
            Rect r = new Rect(0, 0, drs[1].getMinimumWidth() * 2 / 4, drs[1].getMinimumHeight() * 2 / 4);
            //定义一个Rect边界
            drs[1].setBounds(r);
            //给drawable设置边界
//            if (rb.getId() == R.id.rb_m) {
//                r = new Rect(0, 0, drs[1].getMinimumWidth(), drs[1].getMinimumHeight());
//                drs[1].setBounds(r);
//            }

            rb.setCompoundDrawables(null, drs[1], null, null);
            //添加限制给控件
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction fTransaction = fManager.beginTransaction();
        hideAllFragment(fTransaction);
        //Items items = findSelectItem();
        RadioButton rb_main = findViewById(R.id.rb_main);
        RadioButton rb_maininfo = findViewById(R.id.rb_maininfo);
        switch (checkedId) {
            case R.id.rb_main:
                rb_main.setTextColor(Color.parseColor("#FF007AFF"));
                //fg2.onPause();
                fg2 = null;
                if (fg1 == null) {
                    fg1 = new MainRoutineFragment();
                    fTransaction.add(R.id.ly_content, fg1);
                    setFgImage(R.drawable.label_mainprogram_s, R.id.rb_main);
                } else {
                    fTransaction.show(fg1);
                    setFgImage(R.drawable.label_mainprogram_s, R.id.rb_main);
                }
                break;
            case R.id.rb_maininfo:

                rb_main.setTextColor(Color.parseColor("#73000000"));
                if (fg2 == null) {
                    fg2 = new MainInfoFragment();
                    fTransaction.add(R.id.ly_content, fg2);
                    fTransaction.show(fg2);
                    setFgImage(R.drawable.label_session_s, R.id.rb_maininfo);
                } else {
//                    fg2 = new MainInfoFragment();
//                    fTransaction.add(R.id.ly_content, fg2);
                    fTransaction.show(fg2);
                    setFgImage(R.drawable.label_session_s, R.id.rb_maininfo);

                }

                break;
//            case R.id.rb_mainstatus:
//                if (fg3 == null) {
//                    //fg2.onDestroy();
//                    fg3 = new MainStatusFragment();
//                    fTransaction.add(R.id.ly_content, fg3);
//                    fTransaction.show(fg3);
//                    setFgImage(R.drawable.label_state_s, R.id.rb_mainstatus);
//
//                } else {
//                    //fg2.onDestroy();
//                    fTransaction.show(fg3);
//                    setFgImage(R.drawable.label_state_s, R.id.rb_mainstatus);
//                }
//                break;
//            case R.id.rb_system:
//                if (fg4 == null) {
//                    fg4 = new MainSystemFragment();
//                    fTransaction.add(R.id.ly_content, fg4);
//                    setFgImage(R.drawable.label_calibration_s, R.id.rb_system);
//                } else {
//                    fTransaction.show(fg4);
//                    setFgImage(R.drawable.label_calibration_s, R.id.rb_system);
//
//                }
//                break;
            case R.id.rb_mine:
                rb_main.setTextColor(Color.parseColor("#73000000"));
                //fg2.onPause();
                if (fg5 == null) {
                    fg5 = new MyFragment();
                    fTransaction.add(R.id.ly_content, fg5);
                    setFgImage(R.drawable.label_my_s, R.id.rb_mine);

                } else {
                    fTransaction.show(fg5);
                    setFgImage(R.drawable.label_my_s, R.id.rb_mine);
                }
                break;
        }
        fTransaction.commit();
    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    private void setFgImage(int img, int id) {

        hideFgImage(img, id);
    }

    private void hideFgImage(int img, int id) {
//        Drawable rbMain = getResources().getDrawable(img);
//        rbMain.setBounds(0, 0, rbMain.getMinimumWidth()*2/4,rbMain.getMinimumHeight()*2/4);
//        RadioButton rbMain1 = findViewById(id);
//        rbMain1.setCompoundDrawables(null, rbMain, null, null);
        if (rbs.length > 0) {
            for (RadioButton rb : rbs) {

                if (rb.getId() != id) {
                    Drawable rbMain2 = getResources().getDrawable(al.get(rb.getId()));
                    rbMain2.setBounds(0, 0, rbMain2.getMinimumWidth() * 2 / 4, rbMain2.getMinimumHeight() * 2 / 4);
                    RadioButton rbMain1 = findViewById(rb.getId());
                    rbMain1.setCompoundDrawables(null, rbMain2, null, null);
                } else {
                    Drawable rbMain = getResources().getDrawable(img);
                    rbMain.setBounds(0, 0, rbMain.getMinimumWidth() * 2 / 4, rbMain.getMinimumHeight() * 2 / 4);
                    RadioButton rbMain3 = findViewById(id);
                    rbMain3.setCompoundDrawables(null, rbMain, null, null);
                }
            }
        }


    }

    //隐藏所有Fragment
    private void hideAllFragment(FragmentTransaction fragmentTransaction) {
        if (fg1 != null) fragmentTransaction.hide(fg1);
        if (fg2 != null) fragmentTransaction.hide(fg2);
        if (fg3 != null) fragmentTransaction.hide(fg3);
        if (fg4 != null) fragmentTransaction.hide(fg4);
        if (fg5 != null) fragmentTransaction.hide(fg5);

    }

//    public void closeConnection() {
//        if (mReceiveThread != null) {
//            mReceiveThread.threadExit = true;
//            mReceiveThread = null;
//        }
//        if (mOutStream != null) {
//            try {
//                mOutStream.close();
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            mOutStream = null;
//        }
//        if (mInStream != null) {
//            try {
//                mInStream.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            mInStream = null;
//        }
//
//        if (mSocket != null) {
//            try {
//                mSocket.close();
//
//            } catch (IOException e) {
//            }
//            mSocket = null;
//        }
//        //mSocketConnectState = STATE_DISCONNECTED;
//    }
//
//    private void startConnect() {
//        Log.i(TAG, "startConnect");
//        if (ContextVariable.IP == null || ContextVariable.IP.length() == 0) {
//            System.out.println("============================== 请设置socket ip地址 =======================");
//            return;
//        }
//        if (mSocketConnectState != STATE_DISCONNECTED) return;
//        mConnectThread = null;
//        mConnectThread = new SocketConnectThread();
//        mConnectThread.start();
//        mSocketConnectState = STATE_CONNECTING;
//        System.out.println(R.string.state_connecting);
//    }
//
//    class SocketReceiveThread extends Thread {
//        private boolean threadExit;
//        private int blen = 1024;
//
//        public SocketReceiveThread() {
//            threadExit = false;
//        }
//
//        public void run() {
//            byte[] buffer = new byte[blen];
//            Log.i(TAG, "read read runrunrunrunrunrunrunrunrunrunrunrunrunrunrun");
//            while (threadExit == false) {
//                try {
//                    //读取数据，返回值表示读到的数据长度。-1表示结束
//                    int count = mInStream.read(buffer);
//                    if (count == -1) {
//                        Log.i(TAG, "read read -1");
//                        mHandler.sendEmptyMessage(MSG_SOCKET_DISCONNECT);
//                        break;
//                    } else {
//                        String receiveData = new String(buffer, 0, count);
//                        //Log.i(TAG, "==========read buffer:" + receiveData + ",count=" + count);
//                        //Log.i(TAG, "==========read buffer1111:" + buffer );
//
//                        String msgCode = receiveData.substring(2, receiveData.indexOf(";"));
//                        if (msgCode.equals("Success")) {
//                            success_count += 1;
//                            msgCode = "";
//                            if (success_count == 2) {
//                                sendTxt("11,s;");
//                            }
//                            continue;
//                        } else {
//                            int semicolon_inx = ByteUtil.bByteForSemicolon(buffer);
//                            byte[] byte_12 = ByteUtil.subByte(buffer, 0, 2);
//                            byte[] byte_12_add = ByteUtil.subByte(buffer, 3, count - 3);
//                            for (byte b : byte_12_add) {
//                                queue.enQueue(b);
//                            }
//                            String mas_12_key = new String(byte_12);
//                            String mas_12_val = receive_one_field();
//
//                            System.out.println("  msglis_12 ====================" + mas_12_key + " == " + mas_12_val);
//                            mSharedPreferences = getSharedPreferences("setting", Context.MODE_PRIVATE);
//                            SharedPreferences.Editor editor = mSharedPreferences.edit();
//                            editor.putString("box_add", mas_12_val);
//                            editor.commit();
//                            String mBoxAddress = mSharedPreferences.getString("box_add", null);
//                            System.out.println("mBoxAddress");
////                            Device device = new Device();
////                            device.setItemId(itemsId);
////                            device.setBox(mas_12_val);
////                            deviceService.saveOrUpdata(device);
//                        }
//                    }
//                } catch (IOException e) {
//                    System.out.println("+++++++++++++++ receive +++++++++++++++");
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }
//
//        void threadExit() {
//            threadExit = true;
//        }
//    }
//
//
//    private synchronized String receive_one_field() throws InterruptedException, UnsupportedEncodingException {
//        Boolean escaped = false;
//        Boolean command_sep_found = false;
//        ArrayList<Byte> one_field = new ArrayList<Byte>();
//        Boolean bl = true;
//        String msgbt = "";
//        while (bl) {
//            if (!queue.QueueEmpty()) {
//
//                byte tmp = (byte) queue.deQueue();
//                if (escaped) {
//                    if (tmp == 44 || tmp == 59 || tmp == 47) {
//                        one_field.add(tmp);
//                        escaped = false;
//                    } else {
//                        one_field.add(tmp);
//                        escaped = false;
//                    }
//                } else {
//                    if (tmp == 47) {
//                        //遇到 / 就escaped = True 继续循环
//                        escaped = true;
//                    } else if (tmp == 44) {
//                        //break;
//                    } else if (tmp == 59) {
//                        command_sep_found = true;
//                        //break;
//                    } else {
//                        one_field.add(tmp);
//                    }
//                }
//
//            }else {
//                break;
//            }
//        }
//        if (one_field.size() > 0) {
//            msgbt = one_field.toString();
//
//        }
//
//        return msgbt.replace("[","").replace("]","");
//    }
//
//    private String recv_float(ArrayList<Byte> val) {
//        List<Byte> ab5 = dataParseUtil.objToByList(val);
//        byte[] str_one_field5 = dataParseUtil.listTobyte(ab5);
//        return dataParseUtil.recv_float(str_one_field5);
//    }
//
//    class SocketConnectThread extends Thread {
//        @Override
//        public void run() {
//            try {
//                //连接服务端，指定服务端ip地址和端口号。
//                mSocket = new Socket(ContextVariable.IP, mClientPort);
//                //mSocket.setSoTimeout(1000);
//                // 判断客户端和服务器是否连接成功
//                System.out.println(mSocket.isConnected());
//                if (mSocket != null) {
//                    //获取输出流、输入流
//                    mOutStream = mSocket.getOutputStream();
//                    mInStream = mSocket.getInputStream();
//                    if (success_count == 0) {
//                        sendTxt("22,M;");
//                        Thread.sleep(1000);
//                        success_count = 0;
//                        sendTxt("22,M;");
//                    }
//
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTFAIL);
//                return;
//            }
//            Log.i(TAG, "============================== connect success =====================");
//            mHandler.sendEmptyMessage(MSG_SOCKET_CONNECT);
//        }
//
//    }
//
//    private void initHandlerThraed() {
//        //创建HandlerThread实例
//        mHandlerThread = new HandlerThread("handler_thread");
//        //开始运行线程
//        mHandlerThread.start();
//        //获取HandlerThread线程中的Looper实例
//        Looper loop = mHandlerThread.getLooper();
//        //创建Handler与该线程绑定。
//        mSubThreadHandler = new Handler(loop) {
//            public void handleMessage(Message msg) {
//                Log.i(TAG, "mSubThreadHandler handleMessage thread:" + Thread.currentThread());
//                switch (msg.what) {
//                    case MSG_SEND_DATA:
//                        writeMsg((String) msg.obj);
//                        break;
//                    default:
//                        break;
//                }
//            }
//        };
//    }
//
//    private void writeMsg(String msg) {
//        Log.i(TAG, "writeMsg msg=" + msg);
//        if (msg.length() == 0 || mOutStream == null)
//            return;
//        try {
//            mOutStream.write(msg.getBytes());//发送
//            mOutStream.flush();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
//
//    private void sendTxt(String str) {
//        if (mSocket == null) {
//            System.out.println("================================ socket没有连接 ===============================");
//            return;
//        }
//
//        if (str.length() == 0)
//            return;
//        Message msg = new Message();
//        msg.what = MSG_SEND_DATA;
//        msg.obj = str;
//        mSubThreadHandler.sendMessage(msg);
//    }
}
